package oop.db.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import oop.data.LevelConstraint;
import oop.db.Database;

public class LevelConstraintDAO {

	public static LevelConstraint create(long sectionStructureId, int level,
			int count) throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			String sql = "INSERT INTO tblLevelConstraint (sstr_id, ques_level, count) " +
					"VALUES (?, ?, ?)";
			conn = Database.get().getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setLong(1, sectionStructureId);
			stmt.setInt(2, level);
			stmt.setInt(3, count);
			stmt.executeUpdate();
			return new LevelConstraint(sectionStructureId, level, count);
		} finally {
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}

	public static void drop(long sectionStructureId, int level)
			throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			String sql = "DELETE FROM tblLevelConstraint " +
					"WHERE sstr_id = ? AND ques_level = ?";
			conn = Database.get().getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setLong(1, sectionStructureId);
			stmt.setInt(2, level);
			stmt.executeUpdate();
		} finally {
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}

	public static void persist(LevelConstraint constraint) throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			String sql = "UPDATE tblLevelConstraint " +
					"SET count = ?" +
					"WHERE sstr_id = ? AND ques_level = ?";
			conn = Database.get().getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setLong(1, constraint.getSectionStructure().getId());
			stmt.setInt(2, constraint.getLevel());
			stmt.setInt(3, constraint.getCount());
			stmt.executeUpdate();
		} finally {
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}

	public static List<LevelConstraint> fetchBySectionStructure(
			long sectionStructureId) throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String sql = "SELECT sstr_id, ques_level, count " +
					"FROM tblLevelConstraint " +
					"WHERE sstr_id = ?";
			conn = Database.get().getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setLong(1, sectionStructureId);
			rs = stmt.executeQuery();
			return fromResultSet(rs);
		} finally {
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}

	public static List<LevelConstraint> fromResultSet(ResultSet rs)
			throws SQLException {
		List<LevelConstraint> answers = new ArrayList<LevelConstraint>();
		while (rs.next()) { 
			LevelConstraint constraint = new LevelConstraint(rs.getLong(1), rs
					.getInt(2), rs.getInt(3));
			answers.add(constraint);
		}
		return answers;
	}

}
